<template>
  <el-form :model="submit" :rules="rules" v-bind="$attrs" ref="form">
    <el-form-item
      v-for="({ name, label, ...kwargs }, index) in schema"
      :key="index"
      :label="label"
      :prop="name"
    >
      <el-input
        v-bind="kwargs"
        :value="submit[name]"
        @input="handleInput({ name, ...kwargs }, arguments[0])"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
      <el-button @click="handleReset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
/**
 * 这里只是一个代码示例
 */
import _ from "lodash";
export default {
  name: "SubmitForm",
  props: ["value", "beforeSubmit", "rules", "schema"],
  inheritAttrs: true,
  data() {
    return {
      submit: {}
    };
  },
  computed: {
    source() {
      return this.value || {};
    }
  },
  created() {
    this.createData();
  },
  methods: {
    createData() {
      const entries = this.schema.map(({ name }) => {
        return [name, this.source[name]];
      });
      this.submit = Object.fromEntries(entries);
    },
    debounceInput: _.debounce(function () {
      this.$emit("input", { ...this.source, ...this.submit });
    }, 200),
    handleInput({ name }, value) {
      this.submit[name] = value;
      this.debounceInput();
    },
    async handleSubmit() {
      await this.$refs.form.validate();

      const data = { ...this.source, ...this.submit };
      if (typeof this.beforeSubmit === "function") {
        if (!this.beforeSubmit(data)) {
          return;
        }
      }
      this.$emit("input", data);
      this.$emit("submit", data);
    },
    handleReset() {
      this.$refs.form.resetFields();
      this.submit = {};
      this.$emit("input", {});
      this.$emit("reset");
    }
  },
  watch: {
    schema() {
      this.createData();
    },
    value() {
      this.createData();
    }
  }
};
</script>
